package it.poste.il.compensatore.configuration;

import it.poste.il.compensatore.entity.BaseEntity;
import it.poste.il.compensatore.entity.Message;
import it.poste.il.compensatore.entity.MessageBody;
import it.poste.il.compensatore.entity.MessageStatus;
import it.poste.il.compensatore.entity.Operation;
import it.poste.il.compensatore.entity.SDPRequest;
import it.poste.il.compensatore.entity.User;

import java.util.Properties;
import javax.sql.DataSource;

import org.hibernate.dialect.OracleDialect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;

@SuppressWarnings("deprecation")
@Configuration
public class HibernateConfiguration {

	@Value("#{dataSource}")
	private DataSource dataSource;

	@Bean
	public LocalSessionFactoryBean sessionFactoryBean() {
		Properties props = new Properties();

		props.put("hibernate.connection.url", "jdbc:oracle:thin:@localhost:1521:XE");
		props.put("hibernate.default_schema", "comp");
		props.put("hibernate.connection.username", "comp");
		props.put("hibernate.connection.password", "comp");
		props.put("hibernate.connection.driver_class", "oracle.jdbc.OracleDriver");
		props.put("hibernate.dialect", OracleDialect.class.getName());
		props.put("hibernate.connection.autocommit", "false");
		props.put("hibernate.connection.pool_size", 2);
		props.put("hibernate.connection.is-connection-validation-required", "true");
		props.put("hibernate.connection.autoReconnect", "true");
		props.put("hibernate.connection.autoReconnectForPools", "true");
		props.put("hibernate.transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory");
		props.put("hibernate.transaction.auto_close_session", "true");
		props.put("hibernate.cache.provider_class", "org.hibernate.cache.NoCacheProvider");
		props.put("hibernate.current_session_context_class", "thread");
		props.put("hibernate.generate_statistics", "true");
		props.put("hibernate.hbm2ddl.auto", "update");
		props.put("hibernate.show_sql", "true");

		LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
		bean.setAnnotatedClasses(new Class[]{BaseEntity.class, MessageBody.class, Message.class,
				MessageBody.class, MessageStatus.class, Operation.class, SDPRequest.class, User.class});
		
		bean.setHibernateProperties(props);
		bean.setDataSource(this.dataSource);
		//bean.setSchemaUpdate(true);
		return bean;
	}

	@Bean
	public HibernateTransactionManager transactionManager() {
		return new HibernateTransactionManager( sessionFactoryBean().getObject() );
	}

}
